package com.zhuo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class RequestController {
    @GetMapping("goto")
    public String goToPage(HttpServletRequest request){
        request.setAttribute("msg","成功了");
        request.setAttribute("code",200);
        return "forward:/success";  //转发到 /success 请求
    }

    //请求域中的取值方法
    @ResponseBody
    @GetMapping("/success")
    public Map success(@RequestAttribute(value = "msg",required = false) String msg,
                                        @RequestAttribute(value = "code",required = false) Integer code,
                                        HttpServletRequest request){
        Object msg1 = request.getAttribute("msg");
        Object code1 = request.getAttribute("code");

        Map<String,Object> map = new HashMap<>();
        Object hello = request.getAttribute("hello");
        Object name = request.getAttribute("name");
        Object message = request.getAttribute("message");

        map.put("reqMethod_msg",msg1);
        map.put("annotation_msg",msg);
        map.put("hello",hello);
        map.put("name",name);
        map.put("message",message);
        return map;
    }

    @GetMapping("/param")
    public String testPaeam(Map<String,Object> map,
                            Model model,
                            HttpServletRequest request,
                            HttpServletResponse response){
        map.put("hello","word");
        model.addAttribute("name","zhangsan");      //map、model里面的数据会被放在request的请求域  request.setAttribute
        request.setAttribute("massage","helloWorld");
        Cookie cookie = new Cookie("c1","v1");
        cookie.setDomain("localhost");
        response.addCookie(cookie);
        return "forward:/success";
    }

    /**
     * Map<String,Object> map,  Model model, HttpServletRequest request 都是可以给request域中放数据，
     * request.getAttribute();   获取数据
     * MapMethodProcessor、ModelMethodProcessor
     * 无论是 Map、Model 类型的参数，会返回 mavContainer.getModel（）；---> BindingAwareModelMap 是Model 也是Map
     * mavContainer.getModel(); 获取到值的
     */
}
